from django.shortcuts import render
from django.http import HttpResponse
from . CatesViews import  get_cate_all
from . UsersViews import uploads_pic
from .. models import Goods,Cates
# Create your views here.

#商品添加表单
def goods_add(request):

    #获取当前所有分类数据
    data = get_cate_all()

    # 分配数据
    context = {'catelist':data}

    print(data)
    return render(request,'myadmin/goods/add.html',context)


def goods_insert(request):
    try:

        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        #c处理分类对象
        data['cateid'] = Cates.objects.get(id=data['cateid'])
        myfile = request.FILES.get('pic',None)
        if not myfile:
            return HttpResponse('<script>alert("必须上传图片");history.back(-1)</script>')
        #处理 上传文件
        data['pic_url'] = uploads_pic(myfile)



        ob = Goods(**data)
        ob.save()
        print(data)
        return HttpResponse('<script>alert("商品添加成功");location.href="/myadmin/goods/index/";</script>')
    except:
        pass

    return HttpResponse('<script>alert("商品添加失败");history.back(-1);";</script>')

def goods_index(request):
    #从数据库加载数据
    data = Goods.objects.all()


    context = {'goodslist':data}

    return render(request,'myadmin/goods/index.html',context)



